package com.hilton.tigershark;

import java.net.URISyntaxException;
import java.util.Map;

import com.hilton.net.UrlUtils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;

public class UriHandler {
    // Use in overrideUrlLoading
    /* package */ final static String SCHEME_WTAI = "wtai://wp/";
    /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
    /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
    /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
    
    public static boolean shouldOverrideUrlLoading(Context ctx, WebView view, String url) {
        if (url.startsWith(SCHEME_WTAI)) {
            // wtai://wp/mc;number
            // number=string(phone-number)
            if (url.startsWith(SCHEME_WTAI_MC)) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(WebView.SCHEME_TEL +
                        url.substring(SCHEME_WTAI_MC.length())));
                ctx.startActivity(intent);
                return true;
            }
            // wtai://wp/sd;dtmf
            // dtmf=string(dialstring)
            if (url.startsWith(SCHEME_WTAI_SD)) {
                // TODO: only send when there is active voice connection
                return false;
            }
            // wtai://wp/ap;number;name
            // number=string(phone-number)
            // name=string
            if (url.startsWith(SCHEME_WTAI_AP)) {
                // TODO
                return false;
            }
        }

        // The "about:" schemes are internal to the browser; don't want these to
        // be dispatched to other apps. Similarly, javascript: schemas are private
        // to the page
        if (url.startsWith("about:") || url.startsWith("javascript:")) {
            return false;
        }

        Intent intent;
        // perform generic parsing of the URI to turn it into an Intent.
        try {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } catch (URISyntaxException ex) {
            Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
            return false;
        }

        // check whether the intent can be resolved. If not, we will see
        // whether we can download it from the Market.
        if (ctx.getPackageManager().resolveActivity(intent, 0) == null) {
            String packagename = intent.getPackage();
            if (packagename != null) {
                intent = new Intent(Intent.ACTION_VIEW, Uri
                        .parse("market://search?q=pname:" + packagename));
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                ctx.startActivity(intent);
                return true;
            } else {
                return false;
            }
        }

        // sanitize the Intent, ensuring web pages can not bypass browser
        // security (only access to BROWSABLE activities).
//        intent.addCategory(Intent.CATEGORY_BROWSABLE);
//        intent.setComponent(null);
//        try {
//            Log.e(LOGTAG, "are we here fuck that");
//            if (startActivityIfNeeded(intent, -1)) {
//                return true;
//            }
//        } catch (ActivityNotFoundException ex) {
//            // ignore the error. If no application can handle the URL,
//            // eg about:blank, assume the browser can handle it.
//        }

        return false;
    }
    
    public static boolean needsRlz(Uri uri) {
        if ((uri.getQueryParameter("rlz") == null) &&
            (uri.getQueryParameter("q") != null) &&
            UrlUtils.isGoogleUri(uri)) {
            return true;
        }
        return false;
    }

    public static Uri addRlzParameter(Uri uri, String rlz) {
        if (rlz.isEmpty()) {
            return uri;
        }
        return uri.buildUpon().appendQueryParameter("rlz", rlz).build();
    }
    
    /**
     * A UrlData class to abstract how the content will be set to WebView.
     * This base class uses loadUrl to show the content.
     */
    /* package */ static class UrlData {
        final String mUrl;
        final Map<String, String> mHeaders;
        final Intent mVoiceIntent;

        UrlData(String url) {
            this.mUrl = url;
            this.mHeaders = null;
            this.mVoiceIntent = null;
        }

        UrlData(String url, Map<String, String> headers, Intent intent) {
            this.mUrl = url;
            this.mHeaders = headers;
            this.mVoiceIntent = null;
        }

        boolean isEmpty() {
            return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
        }

        /**
         * Load this UrlData into the given Tab.  Use loadUrlDataIn to update
         * the title bar as well.
         */
        public void loadIn(Tab t) {
            t.getWebView().loadUrl(mUrl, mHeaders);
        }
    };
}
